package com.paipai.controller;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWTVerifier;
import com.paipai.dao.UserMapper;
import com.paipai.dto.Auction;
import com.paipai.entity.User;
import com.paipai.utils.CookieUtils;
import com.paipai.utils.IdWorker;
import com.paipai.utils.JwtUtils;
import com.paipai.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/***
 * 参与一次竞价
 */
@Controller
@RequestMapping("/auction")
public class AuctionController {

    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;

    /***
     * 前端传来场次id 用户id 出价 封装进auction 更新redis数据
     * @param
     * @param auction
     * @return
     */
    @RequestMapping("/addAuction")
    @ResponseBody
    public String addAuction(@RequestBody Auction auction, HttpServletRequest req) {

        String token = req.getHeader("token");
        String account = JwtUtils.getAccount(token);
        User user = new User();
        user.setName(account);
        User currentUser = userMapper.selectOne(user);
        auction.setBuyerId(currentUser.getId());
        IdWorker idWorker = new IdWorker(1, 2, 1);
        auction.setId(idWorker.nextId());
        auction.setRoundId(auction.getRoundId());
        auction.setCreateTime(new Date());
        System.out.println("设置后的auction" + auction);
        HashOperations ops = redisTemplate.opsForHash();
        //放入之前查询是否为当前最高价
        Map<String, Auction> entries = ops.entries(auction.getRoundId() + "");
        //如果是空 直接丢进去
        if (0 == entries.size()) {
            ops.put(auction.getRoundId() + "", auction.getId() + "", JSONObject.toJSONString(auction));
            return "ok";
        } else {
            //非空查最高价比较 只有当出价大于目前最高价才put
            List<Auction> list = new ArrayList<>();
            Set<Map.Entry<String, Auction>> entrySet = entries.entrySet();
            for (Map.Entry<String, Auction> auctionEntry : entrySet) {
                Auction auction2 = JSONObject.parseObject(auctionEntry.getValue() + "", Auction.class);
                list.add(auction2);
            }
            list.sort((o1, o2) -> {
                //比较所有的出价 降序
                return Integer.parseInt(o2.getOfferPrice().subtract(o1.getOfferPrice()).toString());
            });
            //排序后拿到最高竞价
            Auction auction2 = list.get(0);
            BigDecimal highestPrice = auction2.getOfferPrice();
            //如果出价小于等于目前最高价 返回错误信息
            if (auction.getOfferPrice().compareTo(highestPrice) < 1) {
                System.out.println("当前最高价为？"+highestPrice+"重试==============");
                return "当前最高价为:" + highestPrice + "。请加价！";
            } else {
                //大KEY为场次id  小KEY为每一次竞价的单独id 小VALUE为竞价具体信息(出价人,出价金额,出价时间)
                ops.put(auction.getRoundId() + "", auction.getId() + "", JSONObject.toJSONString(auction));
                return "ok";
            }
        }


    }

    @RequestMapping("/getCurrentPrice")
    @ResponseBody
    public BigDecimal getCurrentPrice(@RequestParam("roundId") long roundId, @RequestParam("startPrice") BigDecimal startPrice) {
        HashOperations ops = redisTemplate.opsForHash();
        Map<String, Auction> entries = ops.entries(roundId + "");
        if (0 != entries.size()) {
            Set<Map.Entry<String, Auction>> entrySet = entries.entrySet();
            List<Auction> list = new ArrayList<>();
            for (Map.Entry<String, Auction> auctionEntry : entrySet) {
                Auction auction = JSONObject.parseObject(auctionEntry.getValue() + "", Auction.class);
                list.add(auction);
            }
            list.sort((o1, o2) -> {
                //比较所有的出价 降序
                return Integer.parseInt(o2.getOfferPrice().subtract(o1.getOfferPrice()).toString());
            });
            //排序后拿到最高竞价
            Auction auction = list.get(0);

            return auction.getOfferPrice();
        } else {
            return startPrice;
        }

    }
}
